package org.kim.dao;

import org.kim.core.StorageCache;
import org.kim.pojo.Book;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class BookDao extends BaseDao<Book> {

    public boolean bookExists(Book book) {
        if (StorageCache.bookCache.get(book.getName() + "_" + book.getAuthor()) != null) {
            return true;
        } else {
            return false;
        }
    }

    public Book addBook(Book book) throws Exception {
        if (StorageCache.bookCache.get(book.getName() + "_" + book.getAuthor()) != null) {
            Book exits = (Book) StorageCache.bookCache.get(book.getName() + "_" + book.getAuthor());
            Integer originalInventory = exits.getInventory();
            book.setInventory(originalInventory + book.getInventory());
            StorageCache.bookCache.put(book.getName() + "_" + book.getAuthor(), book);
        } else {
            StorageCache.bookCache.put(book.getName() + "_" + book.getAuthor(), book);
        }
        super.persistence(book, "book-" + book.getId());
        return book;
    }

    public List<Book> searchBook(String bookName, String author) {
        Object obj = StorageCache.bookCache.get(bookName + "_" + author);
        Optional<Object> optional = Optional.ofNullable(obj);
        ArrayList<Book> bookList = new ArrayList<Book>();
        if (optional.isPresent()) {
            bookList.add((Book) optional.get());
            return bookList;
        }
        return bookList;
    }

    public List<Book> bookLists() {
        ArrayList<Book> bookList = new ArrayList<Book>();
        StorageCache.bookCache.values().forEach(e -> bookList.add((Book) e));
        return bookList;
    }

    public boolean updateBook(Book book) throws Exception {
        StorageCache.bookCache.put(book.getName() + "_" + book.getAuthor(), book);
        super.persistence(book,"book-" + book.getId());
        return true;
    }

    public boolean deleteBook(Book book) throws Exception {
        StorageCache.bookCache.remove(book.getName() + "_" + book.getAuthor());
        super.deleteSerializeFile(book, "book-" + book.getId());
        return true;
    }
}
